package com.food.foodapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.foodapi.instans.Result;
import com.food.foodapi.mapper.UserMapper;
import com.food.foodapi.model.entity.User;
import com.food.foodapi.model.query.LoginQuery;
import com.food.foodapi.utils.JwtUtil;
import com.food.foodapi.utils.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginQuery loginQuery) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", loginQuery.getUsername()).eq("password", loginQuery.getPassword()));
        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }
        // 这里可以根据用户名和密码做验证，简单起见直接通过
        if (user.getUsername().equals(loginQuery.getUsername()) && user.getPassword().equals(loginQuery.getPassword())) {
            // 生成JWT Token
            String jwtToken = JwtUtil.generateToken(loginQuery.getUsername());
            // 存入Redis
            redisUtil.saveToken(loginQuery.getUsername(), jwtToken);
            return Result.success("登录成功！", jwtToken);
        } else {
            return Result.error(401, "用户名或密码错误");
        }
    }

    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        // 从Redis中删除Token
        String username = (String) session.getAttribute("username");
        System.out.println("username: " + username);
        redisUtil.deleteToken(username);
        return Result.success("登出成功！", null);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        System.out.println("user: " + user.getUsername());
        userMapper.insert(user);
        return Result.success("注册成功", null);
    }
}
